//
//  TestController.m
//  BSProject
//
//  Created by nsm on 2019/7/4.
//  Copyright © 2019 beisheng. All rights reserved.
//

#import "TestController.h"
#import "SuperFormModel.h"

@interface TestWindowView : UIView

@end

@implementation TestWindowView
- (void)willMoveToWindow:(UIWindow *)newWindow {
    NSLog(@"\n------------------------------------\n%s\n%@\n------------------------------------\n",__func__, newWindow);
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    NSLog(@"\n------------------------------------\n%s\n%@\n------------------------------------\n",__func__, newSuperview);
}

- (void)didMoveToWindow {
    NSLog(@"\n------------------------------------\n%s\n%@\n------------------------------------\n",__func__, self.window);

}

- (void)didMoveToSuperview {
    NSLog(@"\n------------------------------------\n%s\n%@\n------------------------------------\n",__func__, self.superview);
}
@end

// Person.h
@interface Person : NSObject
// 未声明
- (void)fuck NS_REQUIRES_SUPER;
- (void)fuckNo;
@end

// Person.m
@implementation Person
+ (void)classMethodTest {
    NSLog(@"run");
}
- (int)instanceMethodTest {
    return 30;
}

- (void)fuck {
    NSLog(@"\n[%@]:%s\n", self.className, __func__);
}

- (void)fuckNo {
    NSLog(@"\n[%@]:%s\n", self.className, __func__);
}

@end

@interface Man : Person

@end

@implementation Man
- (void)fuck {
    [super fuck];
    
    NSLog(@"\n[%@]:%s\n", self.className, __func__);
}
@end

@interface Son : Man
- (void)impTest;
@end

@implementation Son
- (void)fuck {
    [super fuck];
    
    NSLog(@"\n[%@]:%s\n", self.class, __func__);
}

- (void)impTest {
    char *xx = @encode(void);
    NSLog(@"impTest:%s", xx);
    
    Method method = class_getInstanceMethod(self.class, @selector(fuckNo));
    {
        IMP imp = class_getMethodImplementation(self.class, @selector(fuckNo));
        void(*oriSetterImp)(id, SEL);
        oriSetterImp = (void(*)(id, SEL))imp;
        oriSetterImp(self, @selector(fuckNo));
    }

    IMP imp1 = imp_implementationWithBlock(^(id obj1){
        NSLog(@"卧槽,我是新的%@", obj1);
    });
    
    method_setImplementation(method, imp1);
    {
        IMP imp = class_getMethodImplementation(self.class, @selector(fuckNo));
        void(*oriSetterImp)(id, SEL);
        oriSetterImp = (void(*)(id, SEL))imp;
        oriSetterImp(self, @selector(fuckNo));
    }
    
    
    NSLog(@"");
}

@end

@interface TestSub : NSObject

@end

@implementation TestSub
- (void)wocao {
    NSLog(@"卧卧卧卧卧卧卧卧槽");
}
@end

@interface TestButton : UIButton <UITextFieldDelegate>
@property (nonatomic, strong) TestSub *subObj;
@end

@implementation TestButton
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL sel = NSSelectorFromString(@"haha");
        OverrideInstanceMethod(TestButton.class, sel, ^OverrideIMPBlock(OriginalIMPBlock oriImpBlock) {
            return ^(TestButton *objc){
                NSLog(@"我打死你个龟孙");
            };
        });
    });
}
- (BOOL)respondsToSelector:(SEL)aSelector {
    NSLog(@"[%s]%@", __func__, NSStringFromSelector(aSelector));
    return [super respondsToSelector:aSelector];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    NSLog(@"[%s]%@", __func__, NSStringFromSelector(aSelector));
    NSMethodSignature *signature = [super methodSignatureForSelector:aSelector];
    if (signature) return signature;
    
    return [NSMethodSignature signatureWithObjCTypes:"@^v^c"];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    SEL aSelector = anInvocation.selector;
    NSLog(@"[%s]%@", __func__, NSStringFromSelector(aSelector));

    if ([self.subObj respondsToSelector:aSelector]) {
        [anInvocation invokeWithTarget:self.subObj];
    }
}

@end

@interface TestController () <UIPopoverPresentationControllerDelegate>
@property (nonatomic, copy) NSString *retainArg;
@property (nonatomic, strong) MyLinearLayout *layout;
@property (nonatomic, strong) NSMutableArray<NSDictionary *> *selectAttrs;
@property (nonatomic, strong) NSMButton *submitBtn;
@end

@implementation TestController
- (void)setRetainArg:(NSString *)retainArg {
    _retainArg = retainArg;
    NSLog(@"草你妹");
}

#pragma mark - lifeCycle
- (void)loadView {
    self.view = UIScrollView.new;
}

#pragma mark - override
- (void)didInitialize {
    [super didInitialize];
    
    _selectAttrs = @[].mutableCopy;
}

NSString *ClassName(Class cls) {
    return [NSString stringWithUTF8String:class_getName(cls)];
}

#pragma mark - initialization
- (void)wocao:(id)obj {
    self.edgesForExtendedLayout = UIRectEdgeAll;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    TestButton *testBtn = TestButton.new;
    testBtn.subObj = TestSub.new;
    
    SEL haha = NSSelectorFromString(@"haha");
    [testBtn performSelector:haha];
    // BOOL isOk = [testBtn respondsToSelector:haha];
    BOOL isOk = class_respondsToSelector(testBtn.class, haha);
    BOOL isOK1 = [testBtn respondsToSelector:@selector(textFieldShouldBeginEditing:)];
    
    [testBtn performSelector:@selector(wocao)];
    
    UIButton *clsBtn = UIButton.new;
    
    Class clss = object_getClass(clsBtn);
    Class superCls = class_getSuperclass(clss);
    Class metaClsss = objc_getMetaClass(class_getName(clss));
    int i=0;
    while (i<10) {
        BOOL isMeta = class_isMetaClass(clss);
        NSLog(@"类[元类?%@]%@,%p", isMeta?@"是":@"否", ClassName(clss), clss);
        BOOL isMeta1 = class_isMetaClass(superCls);
        NSLog(@"父类[元类?%@]%@,%p", isMeta1?@"是":@"否", ClassName(superCls), superCls);
//        NSLog(@"元类%@,%p", ClassName(metaClsss), metaClsss);
        clss = object_getClass(clss);
        superCls = class_getSuperclass(superCls);
        metaClsss = class_getSuperclass(metaClsss);
        i++;
    }

    
    
    _retainArg = @"xxx";
    self.retainArg = @"bb";
    
    struct UserData {
        NSString *name; // 姓名   8
        int sex;        // 性别   4
        int age;        // 年龄   4
        BOOL isMarried; // 已婚   1
        BOOL isParty;   // 党员   1
        double sum;     // 存款   8
        NSString *addr; // 住址   8
    };    
    struct UserData user;
    user.name = @"小明";
    user.sex = 1;
    user.age = 20;
    user.isMarried = NO;
    user.isParty = NO;
    user.sum = 38.5;
    user.addr = @"湖北襄阳";
    
    size_t len = sizeof(user);
    
    NSData *data = [NSData dataWithBytes:&user length:sizeof(user)];
    
    struct UserData toData;
    [data getBytes:&toData length:sizeof(toData)];
    
    char array[] = {'1', '2', '3'};
    char array2[3] = {'4', '5', '6', '7', '8'};
    NSLog(@"我是结果:%s", array2);
    
    Son *son = Son.new;
    [son fuck];
    [son impTest];
    
    Man *man = Man.new;
    [man fuckNo];
    
    NSPointerArray *p1 = [NSPointerArray weakObjectsPointerArray];
    
    Person *p = Person.new;
    Class cls = Person.class;
    
    [p1 addPointer:(__bridge void * _Nullable)(p)];
    [p1 addPointer:NULL];
        
    NSLog(@"NSPointerArray:%@-%@", @(p1.count), @(p1.allObjects.count));
    
//    p = Man.new;
//    cls = Man.class;
    //                                                                              PerSon    Man
    BOOL res1 = class_respondsToSelector(cls, @selector(instanceMethodTest));      // YES      YES
    BOOL res2 = class_respondsToSelector(cls, @selector(classMethodTest));         // NO       NO
    BOOL res3 = [cls respondsToSelector:@selector(instanceMethodTest)];            // NO       NO
    BOOL res4 = [cls respondsToSelector:@selector(classMethodTest)];               // YES      YES
    BOOL res5 = [p respondsToSelector:@selector(instanceMethodTest)];              // YES      YES
    BOOL res6 = [p respondsToSelector:@selector(classMethodTest)];                 // NO       NO
    BOOL res7 = [cls instancesRespondToSelector:@selector(instanceMethodTest)];    // YES      YES
    BOOL res8 = [cls instancesRespondToSelector:@selector(classMethodTest)];       // NO       NO
    
    /*
     上面这个结论就很牛逼了:
     1.由调用者决定结果
     2.子类响应父类的私有方法
     */
    
    _layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    _layout.backgroundColor = COLOR_4;
    _layout.myHorzMargin = 0;
    _layout.gravity = MyGravity_Horz_Fill;
    [self.view addSubview:_layout];
    
    UIScrollView *sv = UIScrollView.new;
    sv.size = CGSizeMake(kScreenWidth, 100);
    sv.useFrame = YES;
    sv.contentSize = CGSizeMake(kScreenWidth*3, 1);
    sv.backgroundColor = UIColor.yellowColor;
    [_layout addSubview:sv];
    
    TestWindowView *wv = TestWindowView.new;
    wv.size = CGSizeMake(100, 100);
    wv.backgroundColor = UIColor.redColor;
    [sv addSubview:wv];

    
    @nsm_weak(self)
    [_noteCenter addObserverForName:NSCurrentLocaleDidChangeNotification object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification * _Nonnull note) {
        @nsm_strong(self)
        self.retainArg = @"卧槽";
    }];
    
    
    NSMButton *btn = NSMButton.new;
    btn.backgroundColor = RandomColor();
    btn.myTop = kScreenHeight-kNavBarHeight-100;
    btn.myHorzMargin = 100;
    btn.height = 50;
    btn.title = @"弹出";
    [btn addTarget:self action:@selector(pushTest) forControlEvents:UIControlEventTouchUpInside];
//    [btn addTarget:self action:@selector(pushPop:) forControlEvents:UIControlEventTouchUpInside];
    [_layout addSubview:btn];
    
    return;
    
    [_networker POST:@"http://jlys.test.hbbeisheng.com/routine/publics/product_detail?id=200" parameters:nil success:^(NSMResponseObject *responseObject) {
        @nsm_strong(self)
        [self layoutSubviews:responseObject.data];
    } empty:nil failure:nil];
}

- (void)layoutSubviews:(id)obj {
    [_layout removeAllSubviews];
    
    NSMButton *btn = NSMButton.new;
    btn.backgroundColor = UIColor.blueColor;
    btn.wrapContentSize = YES;
    btn.myAlignment = MyGravity_Horz_Center;
    btn.enabled = NO;
    btn.contentEdgeInsets = UIEdgeInsetsMake(8, 12, 8, 12);
    btn.title = @"提交";
    [btn addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    [_layout addSubview:btn];
    _submitBtn = btn;
    
    _selectAttrs = @[].mutableCopy;
    NSArray *attrs = SafeArray(obj[@"productAttr"]);
    for (int i=0; i<attrs.count; i++) {
        NSDictionary *attr = attrs[i];
        [_selectAttrs addObject:@{}];
        
        // 标题
        UILabel *label = UILabel.new;
        label.wrapContentHeight = YES;
        label.text = SafeString(attr[@"attr_name"]);
        [_layout addSubview:label];
        
        // 属性
        MyFloatLayout *layout = [MyFloatLayout floatLayoutWithOrientation:MyOrientation_Vert];
        layout.wrapContentHeight = YES;
        layout.subviewSpace = 12;
        [_layout addSubview:layout];
        
        NSArray *names = SafeArray(attr[@"attr_values"]);
        __block NSMButton *_lastBtn;
        for (NSDictionary *nameDic in names) {
            // 接口控制当前属性能否选中
            BOOL enabled = YES;
            
            NSMButton *btn = NSMButton.new;
            btn.wrapContentSize = YES;
            btn.enabled = enabled;
            btn.tintColor = enabled?COLOR_0:UIColor.redColor;
            btn.adjustsWhenHighlighted = NO;
            btn.adjustsTitleTintColorAutomatically = YES;
            btn.contentEdgeInsets = UIEdgeInsetsMake(8, 12, 8, 12);
            [btn setBackgroundImage:[UIImage imageWithColor:GROUP_TABLECOLOR] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageWithColor:THEME_COLOR] forState:UIControlStateSelected];
            [btn setBackgroundImage:[UIImage imageWithColor:COLOR_3] forState:UIControlStateDisabled];
            btn.title = SafeString(nameDic[@"name"]);
            [layout addSubview:btn];
            ViewCorner(btn, 3);
            
            // 找到第一个可点击的按钮
            if (!_lastBtn && enabled) {
                btn.selected = YES;
                btn.tintColor = COLOR_4;

                _lastBtn = btn;
                self.submitBtn.enabled = YES;
                [self.selectAttrs replaceObjectAtIndex:i withObject:nameDic];
            }
            
            @nsm_weak(self)
            [btn addBlockForControlEvents:UIControlEventTouchUpInside block:^(NSMButton *sender) {
                @nsm_strong(self)
                // 禁止重复选中
                if (sender.selected) return;
                
                // 刷新上个选中状态
                _lastBtn.tintColor = THEME_COLOR;
                _lastBtn.selected = NO;
                
                // 刷新当前选中
                sender.tintColor = COLOR_4;
                sender.selected = YES;
                _lastBtn = sender;
                [self.selectAttrs replaceObjectAtIndex:i withObject:nameDic];
            }];
        }
    }
}

#pragma mark - setter/getter

#pragma mark - network

#pragma mark - method/public

#pragma mark - method/private

#pragma mark - action
- (void)submit {
    NSLog(@"%@", self.selectAttrs);
    
    NSMutableArray *names = @[].mutableCopy;
    for (NSDictionary *attr in self.selectAttrs) {
        [names addObject:SafeString(attr[@"name"])];
    }
    NSLog(@"选中规格:%@", [names componentsJoinedByString:@","]);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 弹出
- (void)pushTest {
    [self.navigationController pushViewController:[NSMViewController new] animated:YES];
}

- (void)testPop:(NSMButton *)sender {
    //新创建一个要显示的控制器
    UIViewController *controller = [[UIViewController alloc] init];
    controller.view.backgroundColor = [UIColor greenColor];
    controller.preferredContentSize = CGSizeMake(300, 300);        //popover视图的大小
    controller.modalPresentationStyle = UIModalPresentationPopover;//这句一定要
    
    // 创建一个显示文字的 Label 添加进去
    UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 300)]; //Label 的尺寸和位置参考 上面的 controller.preferredContentSize
    l.backgroundColor = [UIColor yellowColor];
    l.numberOfLines = 0;
    l.text = @"My name is Van, I am an artist, a performance artist, I am hired for people to fulfill their fantasies, their deep dark fantasies. I was going to be a movie star, you know, was modeling and acting. After a hundred or two auditions and small parts, you know, I decided.. that I had enough, then I ceded into escort work.";
    [controller.view addSubview:l];
    
    UIPopoverPresentationController *popController = controller.popoverPresentationController;
    popController.backgroundColor = RandomColor();
    popController.delegate = self;  //代理一定要
//    popController.sourceView = controller.view; //设置要弹出哪个 视图 (上面自定的控制器的视图)
//    CGRect rect = [sender convertRect:sender.bounds toView:nil];
//    NSLog(@"%@\n%@", NSStringFromCGRect(sender.frame), NSStringFromCGRect(rect));
//    popController.sourceRect = rect;
    popController.sourceView = sender;
    popController.sourceRect = sender.bounds;
    popController.permittedArrowDirections = UIPopoverArrowDirectionDown; //设置弹出框箭头的方向
    popController.passthroughViews = @[sender];
    popController.canOverlapSourceViewRect = YES;
    [self presentViewController:controller animated:YES completion:nil];
}

#pragma mark - 代理
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}

@end
